package com.example.juc;

public class VolatileTest {

    public static void main(String[] args) throws Exception {

        test2();

    }

    //单例模式
    class MyBeanFactory {

        //策略类
        private class MyBean {

        }

        private MyBean instance;

        public MyBean getInstance() {
            if (instance == null) {
                synchronized (this) {
                    if (instance == null) {
                        instance = new MyBean();
                    }
                }
            }
            return instance;
        }

    }

    /**
     * 多线程可见性问题
     */
    private static void test2() {
        InterruptTest.Flag flag = new InterruptTest.Flag();
        Thread t1 = new Thread(() -> {

            System.out.println("开始执行");
            while (!flag.flag) {
                //System.out.println("执行中");
            }
            System.out.println("执行完成");

        });

        t1.start();

        sleep(2000L);
        //打断
        Object o=new Object();
        new Thread(() -> {
            synchronized (o) {
                flag.flag = true;
                System.out.println("中断执行");
            }
        }).start();

    }

    private static void sleep(Long time) {
        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    //多线程重排问题
    public static void test5() throws InterruptedException {
        for (int i = 0; i < 1000000; i++) {
            int x = 0, y = 0, a = 0, b = 0;

            Thread thread = new Thread(() -> {
                test1(a, x, y);
            });
            Thread thread1 = new Thread(() -> {
                test2(b, x, y);
            });

            thread.start();
            thread1.start();

            thread.join();
            thread1.join();
            if (a == 1 && b == 1) {
                System.out.println("a=" + a + "==" + "b=" + b);
            }
        }
    }

    public static void test1(int a, int x, int y) {
        a = y;
        x = 1;
    }

    public static void test2(int b, int x, int y) {
        b = x;
        y = 1;
    }

    //数据依赖问题样例
    public static void test3() {
        int a = 0, b = 0;
        a = 1;  //和b=1没有数据依赖
        b = 1;  //和a=1没有数据依赖
    }

    public static void test4() {
        int a = 0, b = 0;
        a = 1;  //和b=1+a*a没数据依赖
        b = 1 + a * a;  //和a=1有数据依赖
    }
}
